package io.renren.controller;

import io.renren.annotation.Login;
import io.renren.common.utils.Result;
import io.renren.entity.repair.RepairInfoEntity;
import io.renren.service.repair.RepairInfoService;
import io.renren.vo.RepairInfoReqVO;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("api/repairNotice")
@Tag(name = "维修信息表")
public class ApiRepairInfoController {
    @Resource
    private RepairInfoService repairInfoService;
    
    @PostMapping("setRepairInfo")
    @Login
    public Result setRepairInfo(@RequestAttribute("userId") Long userId,
                              @Valid @ModelAttribute RepairInfoReqVO repairInfoReqVO) {
        repairInfoService.saveInfo(repairInfoReqVO, userId);
        return new Result();
    }

    @GetMapping("getRepairInfo")
    @Login
    public Result<List<RepairInfoEntity>> getRepairInfo(@RequestAttribute("userId") Long userId) {
        return new Result().ok(repairInfoService.getListByUserId(userId));
    }
    
    /**
     * 获取工单详情
     * @param id 工单ID
     * @return 工单详情信息
     */
    @GetMapping("getDetailInfo")
    @Login
    public Result getInfoDetail(@RequestParam("id") Long id, @RequestAttribute("userId") Long userId) {
        try {
            // 先获取用户的所有工单
            List<RepairInfoEntity> userOrders = repairInfoService.getListByUserId(userId);
            
            // 在用户的工单中查找指定ID的工单
            RepairInfoEntity detail = userOrders.stream()
                .filter(order -> order.getId().equals(id))
                .findFirst()
                .orElse(null);
            
            if (detail == null) {
                return new Result().error("未找到该工单或无权查看");
            }
            
            return new Result().ok(detail);
        } catch (Exception e) {
            return new Result().error("获取工单详情失败：" + e.getMessage());
        }
    }
    
    /**
     * 管理员/维修人员获取工单详情（不需要userId验证）
     * @param id 工单ID
     * @return 工单详情信息
     */
    @GetMapping("getRootInfoDetail")
    @Login
    public Result getRootInfoDetail(@RequestParam("id") Long id) {
        try {
            // 直接通过ID获取工单详情，不验证所属用户
            RepairInfoEntity detail = repairInfoService.getById(id);
            
            if (detail == null) {
                return new Result().error("未找到该工单");
            }
            
            return new Result().ok(detail);
        } catch (Exception e) {
            return new Result().ok(new ArrayList<>());
        }
    }
}
